<template>
	<view class="container margin-lr-sm">
		<use-navbar title="系统设置"></use-navbar>

		<view class="border-radius margin-top-sm">
			<use-list-title title="个人资料" iconfont=" " @goto="to('/sub-user/pages/setting/personal')"></use-list-title>
			<!-- 	<use-list-title v-if="!false" title="账号与安全" iconfont=" "
				@goto="to('/sub-user/pages/setting/account-security')"></use-list-title> -->
		</view>

		<view class="border-radius margin-top-sm" style="display: none;">
			<use-list-title title="意见反馈" iconfont=" " @goto="to('/sub-user/pages/setting/faq')"></use-list-title>
			<use-list-title :title="appName" iconfont=" " @goto="" :showArrow="false" :tip="version"></use-list-title>
			<use-list-title title="清除缓存" iconfont=" " @goto="clear" :tip="storageSize"></use-list-title>
		</view>
		<view class="border-radius margin-top-sm">
			<use-list-title title="当前公司" iconfont=" " :tip="webSite.ORG" @goto="actionSheetTap(item)">
				<!-- 如有加入新组织，请重启系统更新组织列表 -->
			</use-list-title>

			<!-- <use-list-title title="终端信息" iconfont=" " :showArrow="false" :tip="systemInfo.terminal"></use-list-title> -->
			<template v-if="hasPermissions">
				<use-list-title title="组织成员" iconfont=" " tip=""
					@goto="to('../member/list?id=&type=checkbox&title=公司成员&source=0')"></use-list-title>
			</template>
			<use-list-title title="权限管理" iconfont=" "
				@goto="to('/sub-user/pages/setting/permissions')"></use-list-title>
		</view>
		<view style="height: 10vh;"></view>
		<view class="border-radius margin-top-sm" style="display: none;">
			<view class="use-item log-out-btn tac" @click="tologin">
				<text style="color: #666;">切换账号</text>
			</view>
		</view>

		<view class="border-radius margin-top-sm">
			<view class="use-item log-out-btn tac" @click="tologout">
				<text style="color: red;">退出登录</text>
			</view>
		</view>
		<template v-if="showTestList">
			<view class="container-area">
				<view class="border-radius margin-top-sm bg-main padding-bottom-big">
					<use-list-title title="测试列表" iconfont="" color="#ff6a6c" fwt="600" :showArrow="false" @goto="">
					</use-list-title>
					<view class="stats-area dflex-s bg-main" style="flex-wrap: wrap;">
						<view class="item dflex dflex-flow-c" v-for="(item,idx) in menuList" @click="to(item.url)"
							style="width: 25%;max-width: 25%;min-width: 25%;">
							<uni-icons type="starhalf" size="30" style="color: #78c6bb;" />
							<text>{{item.text}}</text>
						</view>
					</view>

				</view>
				<view v-if="showh5Weixin" class="border-radius margin-top-sm bg-main">
					<!-- 未关注公众号的情况下显示 -->
					<use-list-title title="关注公众号" iconfont="iconweixin" color="#58bc8a" fwt="600" tip="关注领积分"
						@goto="to('/sub-user/pages/setting/setting')"></use-list-title>
				</view>
			</view>
		</template>
	</view>
</template>

<script setup>
	// --选项式 API

	import {
		ref,
		computed,
		reactive,
		onMounted,
		watch,
		getCurrentInstance
	} from 'vue'

	import {
		storeToRefs
	} from 'pinia';
	import {
		useUserStore
	} from '@/store'
	import {
		onLoad,
		onShow,
	} from "@dcloudio/uni-app";
	const {
		ctx,
		proxy
	} = getCurrentInstance();
	console.log("ctx", ctx);
	let UserStore = useUserStore()
	const hasPermissions = ref(true)
	const appName = ref("聚管事")
	const version = ref("1.0.0")
	const webSite = ref('')
	const webSiteList = ref([])
	const systemInfo = ref('')
	const title = ref("标题")
	console.log(systemInfo.value)
	const storageSize = ref(0)


	webSite.value = UserStore.CurrentSite;
	webSiteList.value = UserStore.webSiteList;
	systemInfo.value = UserStore.systemInfo;
	console.log(webSite.value, webSiteList.value)

	onLoad((option) => {
		console.log("B 页面 onLoad:", option);
	});

	onShow(() => {
		console.log("B 页面 onShow");
		checkPermissions();
	});

	const menuList = ref([{
		text: 'demo',
		url: '/sub-test/pages/test/demo'
	}, {
		text: 'demo2',
		url: '/sub-test/pages/test/demo2'
	}, {
		text: 'IM',
		url: '/pages/test/IM'
	}, {
		text: '霍夫曼编码',
		url: '/pages/test/hoffman'
	}, {
		text: '首页',
		url: '/pages/tabbar/launch'
	}, {
		text: '分组',
		url: '/sub-test/pages/test/group'
	}, {
		text: 'chat2',
		url: '/sub-test/pages/test/chat2'
	}, {
		text: 'test3',
		url: '/sub-test/pages/test/test3'
	}, {
		text: '图表',
		url: '/sub-test/pages/test/chart'
	}, {
		text: 'svg',
		url: '/sub-test/pages/test/svg2'
	}, {
		text: '我的任务',
		url: '/sub-user/pages/work/index'
	}, {
		text: '键盘',
		url: '/sub-test/pages/test/adjust'
	}, {
		text: '解码',
		url: '/sub-test/pages/test/decoding'
	}, {
		text: '地址解析',
		url: '/sub-test/pages/map/api'
	}])
	const to = (url) => {
		uni.navigateTo({
			url
		})
	}

	const getStorageSize = () => {
		let storageInfo = uni.getStorageInfoSync();
		let size = storageInfo.currentSize;
		console.log(size);
		if (size < 1024) {
			storageSize.value = size + ' B';
		} else if (size / 1024 >= 1 && size / 1024 / 1024 < 1) {
			storageSize.value = Math.floor(size / 1024 * 100) / 100 + ' KB';
		} else if (size / 1024 / 1024 >= 1) {
			storageSize.value = Math.floor(size / 1024 / 1024 * 100) / 100 + ' M';
		}
	}
	const clear = () => {
		proxy.$utils.alert('确定要清除本地缓存？', () => {
			uni.clearStorageSync();
			try {
				uni.removeStorageSync('use_member_list');
				uni.removeStorageSync('usemall_member');
				uni.removeStorageSync('usemall_member');
			} catch (e) {
				// error
			}
			getStorageSize();
		})
	}

	// 切换账号
	const tologin = () => {
		proxy.$utils.tologin();
	}
	// 退出登录
	const tologout = () => {
		uni.showModal({
			content: '退出登录',
			success: (e) => {
				if (e.confirm) {
					getData({
						storedPro: 'P_Sass_LoginStatus',
						paraNum: 2,
						resultSetNum: 1,
						para1: UserStore.member.member_weixin,
						para2: 0,
					})
					proxy.$utils.msg('退出成功');
					UserStore.logout();

					proxy.$utils.timerout(() => {
						proxy.$utils.tolaunch();
					}, 200);
				}
			}
		});
	}

	const actionSheetTap = () => {
		console.log(webSite.value, webSiteList.value);
		if (!webSiteList.value) return;
		if (webSiteList.value.length == 0) return;
		if (webSiteList.value.length == 1) {
			proxy.$utils.msg("您没有可更换的公司/组织");
			return
		};
		uni.showActionSheet({
			title: '我的公司',
			itemList: fmtItemList(webSiteList.value),
			popover: {
				// 104: navbar + topwindow 高度，暂时 fix createSelectorQuery 在 pc 上获取 top 不准确的 bug
				top: 56,
				left: 15
			},
			success: (e) => {
				console.log(e.tapIndex);
				if (JSON.stringify(webSiteList.value[e.tapIndex]) == JSON.stringify(webSite.value)) return;
				changeWebSite(webSiteList.value[e.tapIndex]);
			}
		})
	}
	const changeWebSite = (site) => {
		console.log(site)
		if (site == UserStore.CurrentSite) return;
		proxy.$utils.timerout(() => {
			loadData('P_Saas_UpdLastLoginCompanyID', {
				unionid: UserStore.member.member_weixin,
				id: site.ORGID
			}, (result) => {
				console.log(result)
				try {
					if (result.status == '1') {
						proxy.$utils.msg("更换成功");
						// --更新中心站，站点信息，后跳转到相应站点
						UserStore.putMemberSite(site);
						webSite.value = site;
						// -切换完站点后回到启动页面，初始化用户信息
						proxy.$utils.timerout(() => {
							proxy.$utils.tolaunch();
						}, 2150)
					}
				} catch (e) {
					//TODO handle the exception
				}
			});
		}, 350)
	}
	const fmtItemList = (list) => {
		let _list = [];
		list.forEach((x, i) => {
			_list.push(x.ORG);
		})
		return _list;
	}

	const loadData = async (type, mode, callback) => {
		let param, _param, _res, __res;
		switch (type) {
			case 'P_Saas_UpdLastLoginCompanyID':
				param = {
					storedPro: 'P_Saas_UpdLastLoginCompanyID',
					paraNum: 2,
					resultSetNum: 1,
					para1: mode.unionid,
					para2: mode.id
				}
				_res = await getMatrixData(param);
				break;
			default:
		}
		if (typeof callback === 'function') {
			// 数据加载完成回调函数
			callback(_res);
		}
	}
	const getData = (param) => {
		console.log(param);
		let url = proxy.$config.baseTestUrl,
			_site = UserStore.CurrentSite.path;
		if (!_site) return;
		let params = {
			loading: false,
			url: '/' + _site + '/webapi/eidData.ashx?oper=LTTG_Multifunction',
			method: 'get',
			data: param
		}
		console.log(url, _site)
		return new Promise((resolve, reject) => {
			try {
				proxy.$api.getData(url, params).then((res) => {
					// console.log(res);
					if (res.status == '1') {
						resolve(res);
					} else {
						reject('获取信息失败' + res.msg)
					}
				})
			} catch (e) {
				console.log(e)
			}
		})
	}
	const getMatrixData = (param) => {
		console.log(param)
		let url = proxy.$config.baseUrl;
		let params = {
			loading: false,
			url: '/webapi/eidData.ashx?oper=LTTG_Multifunction',
			method: 'get',
			data: param
		}
		return new Promise((resolve, reject) => {
			try {
				proxy.$api.getData(url, params).then((res) => {
					// console.log(res);
					if (res.status == '1') {
						resolve(res);
					} else {
						reject('获取信息失败' + res.msg)
					}
				})
			} catch (e) {
				//TODO handle the exception
				console.log(e)
			}
		})
	}
	// 权限判断，需做调整？？？
	const checkPermissions = () => {
		if (UserStore.member.member_rid == '999' || !UserStore.member.member_rid) {
			hasPermissions.value = false;
		} else {
			hasPermissions.value = true;
		}
	}
	const showTestList = computed(() => {
		let _tester = proxy.$config.testers;
		return _tester.indexOf(UserStore.member.member_id) > -1 ? true : false;
	})

	const showh5Weixin = computed(() => {
		return false;
		if (this.member && this.member.member_weixin && this.member.member_weixin.h5) return false;
		return true;
	})
	onMounted(() => {
		getStorageSize();
	})
</script>

<style lang='scss'>
	page {
		background: $page-color-base;
	}

	.use-item {
		height: 90rpx;
		line-height: 90rpx;
		position: relative;
		background: #fff;

		switch {
			transform: translateX(16rpx) scale(.84);
		}

		button {
			line-height: 100rpx;
			background: #fff;
			font-size: 15px;
		}
	}
</style>